
#include "TcpServer.h"
#include "Threadpool.h"
#include <iostream>
using std::cout;
using std::endl;


wd::Threadpool * pThreadpool = NULL;

class Task
{
public:
	Task(const std::string & query,
		 wd::TcpConnectionPtr conn)
	: _query(query)
	, _conn(conn)
	{}

	//process执行的线程是计算线程
	void process()
	{
		//....处理业务逻辑
		//_conn->send(_query);//回显发送成功，相当于在计算线程里面做了IO线程的数据发送的工作,这是一个错误的做法
		//正确的做法是：需要将数据传递给IO线程，再由IO线程进行发送
		//(涉及到的问题是由计算线程通知IO线程)
		
		_conn->sendInLoop(_query);
	}
private:
	std::string _query;
	wd::TcpConnectionPtr _conn;
};

void onConnection(const wd::TcpConnectionPtr &conn)
{
	cout << conn->toString() << endl;
    conn->send("hello, welcome to Chat Server.\r\n");
}

void onMessage(const wd::TcpConnectionPtr &conn)
{
    std::string s(conn->receive());

	Task task(s, conn);
	//完成了IO线程到计算线程的过渡
	pThreadpool->addTask(std::bind(&Task::process, task));
}

void onClose(const wd::TcpConnectionPtr &conn)
{
    printf("%s close\n", conn->toString().c_str());
}

int main(int argc, char const *argv[])
{
	wd::Threadpool threadpool(4, 10);
	threadpool.start();
	
	pThreadpool = &threadpool;

	wd::TcpServer tcpserver("192.168.137.128", 9999);
	tcpserver.setConnectionCallback(&onConnection);
	tcpserver.setMessageCallback(&onMessage);
	tcpserver.setCloseCallback(&onClose);

	tcpserver.start();

    return 0;
}
